<script lang="ts" setup>
  import { onMounted, ref, nextTick } from 'vue'
  import { getDeptListAllService } from '@/api/dept'
  import { params as ParamsType } from '@/types/common'
  import { deptTreeItem } from '@/types/dept'
  import { flatListToTree } from '@/utils/flatListToTree'
  import { Refresh, Search, Delete, Edit, Plus } from '@element-plus/icons-vue'

  defineOptions({ name: 'Tree' })
  const loading = ref(false)
  const treeRef = ref() // 树形组件引用
  // 节点prop配置
  const defaultProps = {
    label: 'name',
    children: 'children',
  }
  // 组件默认配置项
  const emits = defineEmits<{
    (e: 'update:modelValue', value: string | number): void
    (e: 'node-click', data: deptTreeItem, node: any, TreeNode: any): void
  }>()
  const data = ref<deptTreeItem[]>([])
  interface Props {
    params?: ParamsType
    modelValue?: string | number | null
  }
  const props = withDefaults(defineProps<Props>(), {
    modelValue: null,
    params: () => ({} as ParamsType),
  })
  // 判断是否有子节点
  const hasChildren = (node: any) => {
    return node.some((item) => 'children' in item)
  }
  // 获取数据并处理为树形数据
  const fecthTree = async () => {
    const res = await getDeptListAllService(props.params)
    data.value = hasChildren(res) ? res : flatListToTree(res)
    // 数据加载完成后，如果有modelValue，设置当前选中的节点
    // nextTick(() => {
    //   if (treeRef.value && props.modelValue) {
    //     treeRef.value.setCurrentKey(props.modelValue)
    //   }
    // })
  }
  // 点击节点
  const handleNodeClick = (data: deptTreeItem, node: any, TreeNode: any) => {
    emits('update:modelValue', data.id)
    console.log('当前选中节点:', treeRef.value.getCurrentKey())
  }
  //刷新树形数据
  const refreshTree = () => {
    // nextTick(() => {
    //   treeRef.value.setCurrentKey('')
    // })
    // console.log('当前存储节点:', treeRef.value.getCurrentKey())
    emits('update:modelValue', null)
    const nodes = treeRef.value?.store?._getAllNodes?.() || []
    nodes.forEach((item) => {
      item.expanded = false
    })
  }
  onMounted(() => {
    fecthTree()
  })

  // 暴露方法给父组件
  defineExpose({
    fecthTree,
  })
</script>
<template>
  <div class="tree-container">
    <div class="tree-header">
      <slot name="tree-header"></slot>
      <el-button :loading="loading" title="重置" size="small" type="warning" :icon="Refresh" circle @click="refreshTree" />
    </div>
    <el-tree
      ref="treeRef"
      style="max-width: 600px"
      node-key="id"
      :indent="22"
      :data="data"
      :props="defaultProps"
      :expand-on-click-node="false"
      highlight-current
      @node-click="handleNodeClick"
    />
  </div>
</template>
<style lang="scss" scoped>
  .tree-container {
    min-width: 180px;
    margin-top: 60px;
    .tree-header {
      width: 100%;
      box-sizing: border-box;
      display: flex;
      justify-content: end;
      gap: 16px;
      padding: 0 20px;
      margin-bottom: 16px;
    }
  }
</style>
